package com.sbs.gaoxinqutoilet.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.adapter.HomeMenuAdapter;
import com.sbs.gaoxinqutoilet.base.BaseMainFragment;
import com.sbs.gaoxinqutoilet.entity.HomeMenuEntity;
import com.sbs.gaoxinqutoilet.entity.UserEntity;
import com.sbs.gaoxinqutoilet.eventbus.StartNewFragmentEvent;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.JsonUtil;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.NetworkUtils;
import com.sbs.gaoxinqutoilet.utils.SPUtil;
import com.sbs.gaoxinqutoilet.utils.loading.LoadingDialog;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.sbs.gaoxinqutoilet.utils.loading.LoadingDialog.cancelLoadingDialog;

/**
 * Created by 聪明一只哈 on 2018/5/30.
 * Time: 2018/5/30  11:24
 */

public class HomeFragment extends BaseMainFragment {


    private TextView toolTitle;
    private ImageView mMenu;
    private AutoLinearLayout toilet_files;
    private AutoLinearLayout toilet_accept;
    private AutoLinearLayout toilet_check;
    private AutoLinearLayout toilet_build;
    private AutoLinearLayout toilet_count;
    private TextView tv_user_name;
    private TextView tv_user_address;
    private HomeMenuRequest homemenuRequest;
    private RecyclerView rv_home;
    private HomeMenuAdapter homeMenuAdapter;

    private View emptyView;
    private View errorView;
    private View footView;
    private List<HomeMenuEntity> homeMenuNewEntities;
    private View view;
    private String token_data;

    public static HomeFragment newInstance() {

        Bundle args = new Bundle();

        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(inflater);
        return view;
    }


    /**
     * 初始化view
     *
     * @param inflater
     */
    private void initView(LayoutInflater inflater) {
        //-----------ToolBar初始化------------------------------------------------
        toolTitle = (TextView) view.findViewById(R.id.toolbar_title);
        mMenu = (ImageView) view.findViewById(R.id.toolbar_iv_menu);
        mMenu.setScaleType(ImageView.ScaleType.FIT_XY);
        mMenu.setImageResource(R.drawable.shezhi);
        mMenu.setVisibility(View.VISIBLE);

        token_data = SPUtil.getString(Constants.KEY_TOKEN, "");

        if("http://219.148.34.40:8081".equals(HttpApis.IP)){
            toolTitle.setText("厕所革命测试");
        }else{
            toolTitle.setText(getResources().getString(R.string.home_title));
        }
        toolTitle.setTextSize(20f);

        tv_user_name = (TextView) view.findViewById(R.id.tv_user_name);
        tv_user_address = (TextView) view.findViewById(R.id.tv_user_address);
        rv_home = (RecyclerView) view.findViewById(R.id.rv_home_list);

        UserEntity userEntity = SPUtil.getBeanValue(Constants.KEY_USER, UserEntity.class);
        if (userEntity != null) {
            tv_user_name.setText(userEntity.getOpt_name());
            //address改为显示级别   // 301市 302县 303乡 304村
            switch (userEntity.getOpt_level()) {
                case "301":
                    tv_user_address.setText("市级");
                    break;
                case "302":
                    tv_user_address.setText("县级");
                    break;
                case "303":
                    tv_user_address.setText("乡级");
                    break;
                case "304":
                    tv_user_address.setText("村级");
                    break;

                default:

                    break;
            }

            LogUtils.i("获取个人数据", "initView: " + userEntity.toString());

        }
        homeMenuAdapter = new HomeMenuAdapter(R.layout.item_home_menu, homeMenuNewEntities);
        rv_home.setLayoutManager(new LinearLayoutManager(_mActivity));
        rv_home.setAdapter(homeMenuAdapter);
        homeMenuAdapter.disableLoadMoreIfNotFullPage(rv_home);

        emptyView = inflater.inflate(R.layout.view_empty, rv_home, false);
        errorView = inflater.inflate(R.layout.view_error, rv_home, false);
        footView = inflater.inflate(R.layout.view_foot, rv_home, false);


    }


    private void initListener() {

        //menu点击
        mMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new StartNewFragmentEvent(SettingFragment.newInstance()));

            }
        });


        homeMenuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ArrayList<HomeMenuEntity> list = (ArrayList<HomeMenuEntity>) adapter.getData();
                HomeMenuEntity homeMenuEntity = list.get(position);
                switch (homeMenuEntity.getFunc_id()) {

                    case "201":
                        //户厕改造档案
                        EventBus.getDefault().post(new StartNewFragmentEvent(ToiletFilesFragment.newInstance(list.get(position))));
                        break;

                    case "205":
                        //户厕改造检查  接口暂时没完成 放最后完成
                        EventBus.getDefault().post(new StartNewFragmentEvent(ToiletBuildworkInfoFragment.newInstance(list.get(position))));
                        break;


                    case "202":
                        EventBus.getDefault().post(new StartNewFragmentEvent(ToiletBuildAcceptFragment.newInstance(list.get(position))));
                        break;

                    case "401":

                        EventBus.getDefault().post(new StartNewFragmentEvent(ToiletBuildCheckFragment.newInstance(list.get(position))));
                        break;

                    case "306":
                         EventBus.getDefault().post(new StartNewFragmentEvent(ToiletStatisTicalFragmentD.newInstance(list.get(position))));
                        // EventBus.getDefault().post(new StartNewFragmentEvent(ToiletStatisTotalFragment.newInstance(list.get(position))));

                        break;
                    default:

                        break;
                }
            }
        });
    }

    /**
     * 使用懒加载,加载数据
     * 条目点击监听
     *
     * @param savedInstanceState
     */
    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initListener();
    }

    /**
     * 动画结束加载
     * 获取主菜单数据
     *
     * @param savedInstanceState
     */
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        getAllMenuData();
    }


    /**
     * 获取列表数据的所有信息
     */
    private void getAllMenuData() {
        //显示加载对话框
        LoadingDialog.showLoadingDialog(_mActivity);

        String home_fragment = HttpApis.home_fragment;
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        if (homemenuRequest == null) {
            homemenuRequest = new HomeMenuRequest();
        }
        HttpUtils.requestGet(_mActivity, home_fragment, map, homemenuRequest);

    }

    /**
     * 主列表请求数据
     */
    private class HomeMenuRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            LogUtils.i("home", "success: " + jsonStr);
            Type type = new TypeToken<ArrayList<HomeMenuEntity>>() {
            }.getType();

            ArrayList<HomeMenuEntity> homeMenuNewEntities = JsonUtil.json2Collection(jsonStr, type);
            //数据解析
            processData(homeMenuNewEntities);
            //加载完数据取消dialog
            cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("home", "error: " + error);

            if (!NetworkUtils.isConnected(_mActivity)) {
                homeMenuAdapter.setEmptyView(errorView);
            } else {
                homeMenuAdapter.setEmptyView(emptyView);
                homeMenuAdapter.loadMoreFail();
            }
            cancelLoadingDialog();
        }
    }

    /**
     * 加载数据
     *
     * @param homeMenuNewEntities
     */
    private void processData(List<HomeMenuEntity> homeMenuNewEntities) {
        if (homeMenuNewEntities != null && homeMenuNewEntities.size() > 0) {
            homeMenuAdapter.setNewData(homeMenuNewEntities);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();

    }
}
